<template>
  <div>
      <audio id="normalAudio" ref="normalAudioRef" :src="normalAudioSrc"></audio>
    </div>
  <router-view />
</template>

<script setup>
import useSettingsStore from '@/store/modules/settings'
import { handleThemeStyle } from '@/utils/theme'

import { getCurrentInstance, ref, watch, nextTick } from 'vue'

const normalAudioSrc  = ref('https://diancan-1252107261.cos.accelerate.myqcloud.com/mp3/dingdantixing.mp3')

const order_num_a = ref(0)

const { proxy } = getCurrentInstance()
const normalAudioRef = ref(null)
const subNum = ref(0)


watch(subNum,(newValue,oldValue) => {
  nextTick(() => {
    if(newValue > 0){
       document.addEventListener('click', () => {
        play()
        document.removeEventListener('click', playAudioOnInteraction)
      }, { once: true })
    }
  })
  
})
onMounted(() => {
 proxy.goEasy.connect({
  onSuccess: function () { //连接成功
  subMessage()
    console.log("GoEasy connect successfully.") //连接成功
  },
  onFailed: function (error) { //连接失败
   console.log("Failed to connect GoEasy, code:"+error.code+ ",error:"+error.content);
  }
});
  nextTick(() => {
    // 初始化主题样式
    handleThemeStyle(useSettingsStore().theme)
  })
})

const subMessage = () => {
  //订阅消息
  proxy.goEasy.pubsub.subscribe({
    channel: "test_channel",//替换为您自己的channel
    onMessage: function (message) { //收到消息
      const order_num_a = localStorage.getItem('order_num') || 0
      localStorage.setItem('order_num', Number(order_num_a) + 1)
      subNum.value = JSON.parse(localStorage.getItem('order_num'))
    },
    onSuccess: function () {
      console.log("Channel订阅成功。");
    },
    onFailed: function (error) {
      console.log("Channel订阅失败, 错误编码：" + error.code + " 错误信息：" + error.content)
    }
  });
}


const play = () => {
  // 播放音频
  const audio = normalAudioRef.value
  audio.play()
}



</script>
